package fencer911;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.awt.image.BufferedImage;
/**
 * @author <a href="https://github.com/fencer911/transfer-file-by-qrcode">transfer-file-by-qrcode</a>
 * @since 2020/03
 */
public class CodeUtils {
    public static BufferedImage createQRCode(String content, BarcodeFormat format, QrConfig config) {
        if (null == config) {
            config = new QrConfig();// default config
        }
        final BitMatrix bitMatrix = encode(content, format, config);
        final BufferedImage image = toImage(bitMatrix, config.foreColor, config.backColor);
        return image;
    }
    public static BitMatrix encode(String content, BarcodeFormat format, QrConfig config) {
        final MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix;
        try {
            bitMatrix = multiFormatWriter.encode(content, format, config.width, config.height, config.toHints());
        } catch (WriterException e) {
            throw new QrCodeException(e);
        }

        return bitMatrix;
    }
    public static BufferedImage toImage(BitMatrix matrix, int foreColor, int backColor) {
        final int width = matrix.getWidth();
        final int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? foreColor : backColor);
            }
        }
        return image;
    }
}
